package com.hermes.comics.dialogs;

import android.app.Activity;

import android.content.Context;
import android.content.DialogInterface;

import android.net.Uri;

import android.widget.BaseAdapter;
import android.widget.Toast;

import com.hermes.comics.data.Catalog;
import com.hermes.comics.data.Issue;
import com.hermes.comics.data.IssueTag;
import com.hermes.comics.data.Item;
import com.hermes.comics.data.Serie;
import com.hermes.comics.data.SerieTag;

import java.net.HttpURLConnection;

/**
 */
public class SaveItemDialog extends RemoteCatalogDialog implements RemoteCatalogDialog.Interface {
   
  public interface OnSaveData {
    public void onSave();
  }

  private final Item item;
  private final OnSaveData onSaveData;

  public static RemoteCatalogDialog buildForSerie(Activity activity, Serie serie, OnSaveData onSaveData) {
    RemoteCatalogDialog dialog = new SaveItemDialog(activity, serie, onSaveData);
    dialog.setTitle("Updating serie " + SerieTag.TITLE.value(serie));
    return dialog;
  }

  public static RemoteCatalogDialog buildForIssue(Activity activity, Issue issue, OnSaveData onSaveData) {
    RemoteCatalogDialog dialog = new SaveItemDialog(activity, issue, onSaveData);

    Serie serie = Catalog.getInstance().getSerie(issue);
    dialog.setTitle(
        "Updating issue " + IssueTag.KEY.value(issue) + " of " + SerieTag.TITLE.value(serie));
    return dialog;
  }

  private SaveItemDialog(Activity activity, Item item, OnSaveData onSaveData) {
    super(activity);
    this.item = item;
    this.onSaveData = onSaveData;
  }

  @Override
  public void onPreExecute() {
  }

  @Override
  public String getUrl() {
    return item.urlForEdit();
  }

  @Override
  public void onCancelled() {
    dismiss();
  }

  @Override
  public void onFailure(UrlWrapper result) {
    Toast.makeText(getContext(), "Error http status = " + result.httpStatus(), Toast.LENGTH_LONG).show();
    dismiss();
  }

  @Override
  public void onSuccess(UrlWrapper result) {
    onSaveData.onSave();
    Catalog.getInstance().commit(item);
    dismiss();
  }

  @Override
  public void show() {
    super.show();
    execute(this);
  }
}
